//
//  PainterViewController.m
//  TestDemo
//
//  Created by zhangwenqiao on 2018/12/5.
//  Copyright © 2018年 zhangwenqiao. All rights reserved.
//

#import "PainterViewController.h"
#import "TextViewController.h"
#import "QiniuPicUPload.h"
#import <QiniuSDK.h>
#import <TZImagePickerController.h>
#import "ImageExamineViewController.h"
#import "HomeViewController.h"
#import "RequstMainTool.h"
#import "QiNiuUploadTool.h"
#import <SDWebImage.h>
#import "PainModel.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import "PainterDetailViewController.h"

@interface PainterViewController () <UITableViewDelegate, UITableViewDataSource,TZImagePickerControllerDelegate>

@property (nonatomic, strong) NSMutableArray *iamgeMArray;
@property (nonatomic, strong) NSMutableArray *artworkMArray;
@property (nonatomic, strong) NSMutableArray *keysMArray;
@property (nonatomic, strong) NSMutableArray *imageKey;
@property (nonatomic) BOOL orUpdata;
@property (nonatomic, strong) NSMutableArray *nameArray;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) PainModel *painModel;
@property (nonatomic, strong) QiNiuUploadTool *qiNiu;

@end

@implementation PainterViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"画师"  image:[[UIImage imageNamed:@"tabbar_floer_0"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"tabbar_foler_1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"画师";
    
    [self dataInit];
    [self setTableViewUI];
}

- (void)dataInit {
    self.iamgeMArray = [NSMutableArray array];
    self.artworkMArray = [NSMutableArray array];
    self.keysMArray = [NSMutableArray array];
    self.dataSource = [NSMutableArray array];
    self.orUpdata = NO;
    self.nameArray = @[@"跳转试验界面", @"选择器", @"查看器", @"七牛上传", @"Home跳转", @"2003分类数据请求", @"6003月榜数据请求", @"原生6003请求", @"七牛封装上传", @"跳转导航栏"].copy;
}

- (void)setTableViewUI {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

#pragma mark --tableViewDelegate--
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }else if (section == 1) {
        if (self.dataSource.count > 0) {
            return self.dataSource.count;
        }else {
            return 0;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        cell.textLabel.text = self.nameArray[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:@"tabbaraddgroupbtn"];
        return cell;
    }else if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        self.painModel = [PainModel mj_objectWithKeyValues:self.dataSource[indexPath.row]];
        cell.textLabel.text = [NSString stringWithFormat:@"画师:%@   ID:%ld", self.painModel.nickName, self.painModel.ID];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.painModel.imgPath] placeholderImage:[UIImage imageNamed:@"tabbaraddgroupbtn"]];
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self pushAction:nil];
        }else if (indexPath.row == 1) {
            [self pickImageView:nil];
        }else if (indexPath.row == 2) {
            [self imageDispose:nil];
        }else if (indexPath.row == 3) {
            [self uploadActionOne:nil];
        }else if (indexPath.row == 4) {
            [self uploadActionTwo:nil];
        }else if (indexPath.row == 5) {
            [self request2003];
        }else if (indexPath.row == 6) {
            [self request6003];
        }else if (indexPath.row == 7) {
            [self requestProtogenesis6003];
        }else if (indexPath.row == 8) {
            [self qiNiuUpload];
        }else if (indexPath.row == 9) {
            [self pushToDetailView];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}


- (IBAction)pushAction:(id)sender {
    [self.navigationController pushViewController:[TextViewController new] animated:YES];
}

- (IBAction)pickImageView:(id)sender {
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
    imagePicker.allowPickingOriginalPhoto = YES;
    imagePicker.allowPickingVideo = NO;
    imagePicker.allowPickingImage = YES;
    imagePicker.showSelectedIndex = YES;
    imagePicker.showPhotoCannotSelectLayer = YES;
    imagePicker.cannotSelectLayerColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    imagePicker.allowTakePicture = NO;
    //    imagePicker.preferredLanguage = @"zh-Hans";
    // 这是一个navigation 只能present
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark --pickImageDelegate--
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    NSLog(@"缩略photos----%@", photos);
    NSLog(@"原图assets----%@", assets);
    self.iamgeMArray = photos.copy;
    self.artworkMArray = assets.copy;
    
}

- (IBAction)imageDispose:(id)sender {
    ImageExamineViewController *imageExamine = [ImageExamineViewController initWithImageExamineViewController:self.iamgeMArray arrtwork:self.artworkMArray];
    [self.navigationController pushViewController:imageExamine animated:YES];
}

- (IBAction)uploadActionOne:(id)sender {
    [self uploadImages:self.iamgeMArray atIndex:0 token:@"RCYJEHvGdufWjrrbpq3rcMuCDM7vpPyBgxLFuSJv:-iB3FGrjHf7YzgkuKXKcaFy2gIg=:eyJzY29wZSI6ImhvbmV5d2ViIiwiZGVhZGxpbmUiOjI2MzQ1MzQxODl9" uploadManager:[[QNUploadManager alloc] init] keys:self.keysMArray];
}

- (IBAction)uploadActionTwo:(id)sender {
    if (self.orUpdata == NO) {
        //图片上传之后
        [self. navigationController pushViewController:[HomeViewController initWithImageHomeViewController:self.imageKey arrtwork:self.artworkMArray] animated:YES];
    }else {
        NSLog(@"图片上传尚未成功");
    }
    
}

- (IBAction)uploadActionThree:(id)sender {
    
}


- (void)uploadImages:(NSArray *)images atIndex:(NSInteger)index token:(NSString *)token uploadManager:(QNUploadManager *)uploadManager keys:(NSMutableArray *)keys{
    if (images.count <= 0) {
        return;
    }
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    //图片转化是否有损
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    //时间戳
    NSTimeInterval time= [[NSDate new] timeIntervalSince1970];
    //图片路径拼接
    NSString *filename = [NSString stringWithFormat:@"%@_%ld_%.f.%@",@"status",686734963504054272,time,@"jpg"];
    [uploadManager putData:data key:filename token:token
                  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (info.isOK) {
                          NSString *imageUrl = [NSString stringWithFormat:@"http://web.wohoney.com/%@", key];
                          [keys addObject:imageUrl];
                          NSLog(@"idInex %ld,OK",index);
                          imageIndex++;
                          if (imageIndex >= images.count) {
                              NSLog(@"上传完成");
                              self.imageKey = [NSMutableArray arrayWithArray:keys];
                              self.orUpdata = YES;
                              for (NSString *imgKey in keys) {
                                  NSLog(@"%@",imgKey);
                              }
                              
                              return ;
                          }
                          [self uploadImages:images atIndex:imageIndex token:token uploadManager:uploadManager keys:keys];
                      }
                      
                  }
                    option:nil];
}

- (NSArray *)forImageURL:(NSMutableArray *)imageKey {
    NSMutableArray *array = [NSMutableArray array];
    if (imageKey.count > 0) {
        for (int i = 0; i < imageKey.count; i++) {
            NSDictionary *dic = [NSDictionary dictionary];
            NSString *key = imageKey[i];
            NSString *imageUrl = [NSString stringWithFormat:@"http://web.wohoney.com/%@", key];
            [dic setValue:imageUrl forKey:[NSString stringWithFormat:@"image%d", i]];
            [array addObject:dic];
        }
        NSLog(@"数据源--%@", array);
        return [NSArray arrayWithArray:array];
    }else {
        return nil;
    }
}

//数据6003 月榜
- (void)request6003 {
    [RequstMainTool requestUrl:nil Action:6002 BodyDic:nil Token:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"请求成功responseObject--%@", responseObject);
        NSDictionary *dic = responseObject;
        NSLog(@"dic--%@", dic);
        self.dataSource = [NSMutableArray mj_objectWithKeyValues:dic[@"data"]];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"请求失败error--%@", error);
        
    }];
}

- (void)request2003 {
    [RequstMainTool requestUrl:nil Action:2003 BodyDic:nil Token:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"请求成功responseObject--%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"请求失败error--%@", error);
        
    }];
}

- (void)requestProtogenesis6003 {
   NSURL *urlStr = [[NSURL alloc]initWithString:@"http://47.98.243.228:8081/app/v1"];
    [RequstMainTool protogenesis:urlStr Action:6003 BodyDic:nil Token:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"请求成功responseObject--%@", responseObject);
        NSDictionary *dic = [self dictionaryWithJsonString:responseObject];
        NSLog(@"dic--%@", dic);
        self.dataSource = [NSMutableArray mj_objectWithKeyValues:dic[@"data"]];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"请求失败error--%@", error);
    }];
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)qiNiuUpload {
    self.qiNiu = [[QiNiuUploadTool alloc] init];
    NSLog(@"是否上传成功--%d", self.qiNiu.orUpdata);
    [self.qiNiu addObserver:self forKeyPath:@"orUpdata" options:NSKeyValueObservingOptionNew  | NSKeyValueObservingOptionOld context:nil];
    [self.qiNiu uploadImages:self.iamgeMArray atIndex:0 token:@"RCYJEHvGdufWjrrbpq3rcMuCDM7vpPyBgxLFuSJv:-iB3FGrjHf7YzgkuKXKcaFy2gIg=:eyJzY29wZSI6ImhvbmV5d2ViIiwiZGVhZGxpbmUiOjI2MzQ1MzQxODl9" uploadManager:[[QNUploadManager alloc] init] keys:self.keysMArray];
}

//一旦属性被操作了，这里会自动响应（上面设置观察的属性才会在这响应）
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"orUpdata"] && self.qiNiu == object) {
        //表示上传图片完成
        NSLog(@"上传完成--%@", [change objectForKey:NSKeyValueChangeNewKey]);
        NSLog(@"上传未完成--%@", [change objectForKey:NSKeyValueChangeOldKey]);
        
    } else if ([keyPath isEqualToString:@"myView"]) {
        NSLog(@"我的视图");
    }
}

//移除
- (void)dealloc {
    [self.qiNiu removeObserver:self forKeyPath:@"orUpdata"];
}

- (void)pushToDetailView {
    PainterDetailViewController *painterDetail = [PainterDetailViewController new];
    painterDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:painterDetail animated:YES];
    
}

@end
